package com.mx.base.language.script

import org.apache.poi.ss.usermodel.WorkbookFactory
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import org.dom4j.DocumentHelper
import org.dom4j.io.OutputFormat
import org.dom4j.io.SAXReader
import org.dom4j.io.XMLWriter
import java.io.File
import java.io.FileOutputStream


/**
 * @author: xiao.ma
 * Date: 2022/1/25 19:18
 * Desc:只适合读取由 ExportScript脚本且 byLanguageCategory=false 到出的excel
 */
object ImportScript {

    /**
     * 从Excel读取国家化语言包
     * @param excelFilePath excel文件路径
     * @return
     */
    fun readLanguageFromExcel(
        excelFilePath: String,
        target: List<String>
    ): MutableMap<String, MutableMap<String, String>> {
        val languageMap = mutableMapOf<String, MutableMap<String, String>>()
        val workbook = WorkbookFactory.create(File(excelFilePath))
        //val workbook = XSSFWorkbook(File(excelFilePath))
        workbook.sheetIterator().forEach { sheet ->
            println("====>${sheet.sheetName}")
            val header = sheet.getRow(0)
            if (header != null) {
                val firstRowIndex = sheet.firstRowNum + 2 //前两行是values- 和对应语言翻译所以不读
                val lastRowIndex = sheet.lastRowNum
                for (rowIndex in firstRowIndex..lastRowIndex) {
                    val row = sheet.getRow(rowIndex)
                    if (row != null) {
                        val firstCellNum = row.firstCellNum
                        val lastCellNum = row.lastCellNum
                        val key = row.getCell(firstCellNum.toInt())?.stringCellValue
                        // println("==>key=$key")
                        if (key != null) {
                            for (index in firstCellNum + 1 until lastCellNum) {

                                val mapKey = header.getCell(index)?.stringCellValue
                                if (mapKey != null
                                    && mapKey.startsWith("values")
                                    && (target.contains(mapKey) || target.isEmpty())//如果目标翻译为空则默认加载所有语言包
                                ) {
                                    var translateMap = languageMap[mapKey]
                                    if (translateMap == null) {
                                        println("------>init $mapKey translateMap")
                                        translateMap = mutableMapOf()
                                        languageMap[mapKey] = translateMap
                                    }
                                    val languageValue = row.getCell(index)?.stringCellValue
                                    if (languageValue != null) {
                                        translateMap[key] = languageValue
                                    }
                                }
                            }
                        }
                    }

                }
            }
        }
        workbook.close()
        return languageMap
    }


    fun genStringsXml(
        resPath: String,
        baseLanguage: String,
        excelFilePath: String,
        target: List<String>,
        update: Boolean = false,
        fill: Boolean = false
    ) {
        val baseXmlMap = XmlHelper.readStringXml("$resPath/$baseLanguage/strings.xml")
        if (baseXmlMap.isEmpty()) {
            println("没有需要翻译的文本")
            return
        }
        val languageMap = readLanguageFromExcel(excelFilePath, target)
        if (languageMap.isEmpty()) {
            println("语言包数据为空")
            return
        }
        languageMap.forEach { map ->
            XmlHelper.genTargetStringsXml(
                "$resPath/${map.key}/strings.xml",
                baseXmlMap,
                map.value,
                update,
                fill
            )

        }


    }


    class Builder {
        private var projectPath = ""
        private var resPath = "src/main/res"
        private var baseLanguage = "values-zh-rCN"
        private var target = mutableListOf<String>()
        private var excelPath = ""

        private var update = false

        private var fill = false

        fun setProjectPath(projectPath: String): Builder {
            this.projectPath = projectPath
            return this
        }

        fun setBaseLanguage(baseLanguage: String): Builder {
            this.baseLanguage = baseLanguage
            return this
        }

        fun setTargets(target: MutableList<String>): Builder {
            this.target = target
            return this
        }

        fun setExcelPath(excelFilePath: String): Builder {
            this.excelPath = excelFilePath
            return this
        }

        fun setUpdate(update: Boolean): Builder {
            this.update = update
            return this
        }

        fun setFill(fill: Boolean): Builder {
            this.fill = fill
            return this
        }

        private fun fileFilter(file: File): Boolean {
            return file.isDirectory
                    && !file.name.startsWith(".")
                    && File(
                file.absolutePath,
                "$resPath/$baseLanguage/strings.xml"
            ).run {
                exists() && isFile
            }
        }

        fun build() {
            File(projectPath)
                .listFiles { file -> fileFilter(file) }?.forEach {
                    genStringsXml(
                        resPath = "${it.absoluteFile}/$resPath",
                        baseLanguage = baseLanguage,
                        excelFilePath = excelPath,
                        target = target,
                        update = update,
                        fill = fill
                    )
                }

        }
    }
}


fun main() {

    ImportScript.Builder()
        .setExcelPath("D:\\Language\\values-ro-rRO.xlsx")
        .setProjectPath("C:\\Android\\wk\\peanut_gbg_peanut_v9.12.10.1x")
        .setBaseLanguage("values-zh-rCN")
        .setTargets(mutableListOf("values","values-ro-rRO"))
        .setUpdate(true)
        .setFill(true)
        .build()

}
